package com.edu.filter;

import com.edu.commons.Constants;
import com.edu.commons.ServiceCode;
import com.edu.commons.ServiceException;
import com.edu.utils.JWTUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;


/**
 * @ProjectName: myApp
 * @Titile: GatewayGlobalFilter
 * @Author: Administrator
 * @Description: 全局过滤器
 */
// GlobalFilter,全局过滤器接口；Ordered:优先级接口，数字越小优先级越高
@Slf4j
@Component //组件
public class GatewayGlobalFilter implements GlobalFilter, Ordered {

    private final JWTUtils jWTUtils;

    public GatewayGlobalFilter(JWTUtils jWTUtils) {
        this.jWTUtils = jWTUtils;
    }

    @Override
    public int getOrder() {
        return 10;//设置执行顺序，优先级高的先执行
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径
        String uri = exchange.getRequest().getPath().toString();
        log.info("请求路径:{}",uri);
        //放行不需要过滤的资源
        //可以在这里加白名单
        if(uri.startsWith("/api/user/login") ||
                uri.startsWith("/api/user/register")
               // || uri.startsWith("/product/discount")
                ){
            return chain.filter(exchange);//到下一个过滤器
        }
        //获取请求头信息
        HttpHeaders headers = exchange.getRequest().getHeaders();
        //打印所有的请求头信息
        log.info("headers:{}",headers);
        //获取用户token
        String token = headers.getFirst(Constants.AUth_TOKEN);
        log.info("Authorization:{}", token);
        if(!StringUtils.hasLength(token)){
            log.info("--token为空---");
            //exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            throw new ServiceException(ServiceCode.ERROR_UN_AUTHORIZED,"token不能为空");
        }
        //校验token
        try {
            jWTUtils.validateToken(token);
        } catch (Exception e) {
            throw new  ServiceException(ServiceCode.ERROR_UN_AUTHORIZED,"token不合法");
        }
        // todo 将token中的信息取出来，存在请求头，往后面传递
        String username = jWTUtils.parseToken(token);
        exchange.getRequest().getHeaders().set("X-User-Username",username);
        //验证通过
        return chain.filter(exchange);
    }

}
